﻿using System;
using System.Collections;
using System.Data;
using Telerik.Web.UI;
using System.Web.UI;
using KPIS.GERP.GAMS.DAL;
using KPIS.GERP.GAMS.APP.App_UI.Commons;
using System.Collections.Generic;

namespace KPIS.GERP.GAMS.APP.App_UI.Forms
{
    public partial class Reports3 : System.Web.UI.Page
    {
        Commons.Main main = new Commons.Main();
        D_ACM_MAS_FISCAL_Period d_acm_fiscal_period = new D_ACM_MAS_FISCAL_Period();
        D_BGM_MAS_Source source = new D_BGM_MAS_Source();
        D_ACM_GENERAL_Ledger lg = new D_ACM_GENERAL_Ledger();
        MailMerge mailMerge = new MailMerge();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadGrdBgmSource();
            }
        }

        protected void LoadGrdBgmSource()
        {
            grdBgmSource.DataSource = source.GetList();
            grdBgmSource.DataBind();
        }

        protected void btnReport_Click(object sender, EventArgs e)
        {
            string strBgmSourceSeq = "";
            DateTime? dtStartDate = dtpStartDate.GetDateValue();
            DateTime? dtEndDate = dtpEndDate.GetDateValue();

            if (grdBgmSource.SelectedItems.Count == 0 || !dtStartDate.HasValue || !dtEndDate.HasValue)
            {
                lblWarning.Visible = true;
                return;
            }
            else
            {
                for (int i = 0; i < grdBgmSource.SelectedItems.Count; i++)
                {
                    GridDataItem item = (GridDataItem)grdBgmSource.SelectedItems[i];
                    strBgmSourceSeq += item["bgm_source_seq"].Text + (i == grdBgmSource.SelectedItems.Count - 1 ? "" : ",");
                }
            }

            Borrow(strBgmSourceSeq, dtStartDate.Value, dtEndDate.Value);
        }

        #region report
        private void Borrow(string strBgmSourceSeq, DateTime dtStartDate, DateTime dtEndDate)
        {
            DataTable dtb = lg.ReportBorrow(strBgmSourceSeq, dtStartDate, dtEndDate);
            Dictionary<string, DataTable> dic = new Dictionary<string, DataTable>();
            dic.Add("A5", dtb);

            Dictionary<string, string> dic2 = new Dictionary<string, string>();

            dic2.Add("A1", DateTime.Today.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
            dic2.Add("A2", string.Format("ทะเบียนคุมเงินยืม ระหว่างวันที่ {0} ถึงวันที่ {1}", dtStartDate.ToLongDateString(), dtEndDate.ToLongDateString()));

            mailMerge.MergeExcel(Response, Server.MapPath("~/Reports/Templates/Borrow.xlsx"), string.Format("Borrow-{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), dic, dic2);
        }
        #endregion
    }
}
